import { IPagerParams } from "src/models/pager";
import * as Joi from "@hapi/joi";
import { validate } from "./joi-util";
import { throwValidateException } from "./exception-util";
import * as JSON5 from 'json5';

export function getPagerParams (pagerStr: string, field = 'pager'): IPagerParams {
  if (!pagerStr) {
    return null;
  }
  let json = null;
  try {
    json = JSON5.parse(pagerStr);
  } catch (e) {
    console.error(e);
    throwValidateException([{
      field,
      message: `${field} is not right format`,
      code: 'json.syntax.error',
    }]);
  }
  if (!json) {
    return null;
  }
    
  const schema = Joi.object({
    pageNo: Joi.number().integer().min(1),
    pageSize: Joi.number().integer().min(1),
    orderBy: Joi.array().items({
      field: Joi.string().min(1).required(),
      isDesc: Joi.bool().required(),
    }),
    search: Joi.array().items({
      key: Joi.string().min(1).required(),
      op: Joi.string().min(1).required(),
      value: Joi.string().min(1).required(),
    }),
  });
  return validate(schema, json);
}

